﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web.Mvc;
using DHAA.Areas.Administrator.Models;
using DHAA.Global;


namespace DHAA.Areas.Administrator.Controllers
{
    public class AdminController : Controller
    {

        // DECLARE //
        private SqlConnection sqlConnection;
        readonly GlobalController globalController = new GlobalController();
        private SqlCommand sqlCommand;
        private SqlDataAdapter sqlDataAdapter;
        private static AdminModels _admin { set; get; }

        //********* LOGIC METHOD *********//

        //** FAKE SLEEP FOR AJAX LOAD 
        public void sleep()
        {
            System.Threading.Thread.Sleep(2000);
        }

        //** CONNECTING SQL **//

        public SqlConnection getConnection()
        {
            return globalController.getConnection();
        }

        //*********** ACTION RESULTS ************/
        //-- Index --//
        public ActionResult Index()
        {
            return View();
        }

        // GET : LOGIN
        public ActionResult Login()
        {
            sleep();
            return PartialView("Login");
        }
        // POST: LOGIN
        [HttpPost]
        public ActionResult PostLogin(AdminModels admin)
        {
            sleep();
            if (admin.Username == null || admin.Password == null)
            {
                return PartialView("Login");
            }

            admin.Password = globalController.password2md5(admin.Password);

            try
            {
                sqlConnection = getConnection();
                var parameters = new SqlParameter[2];
                parameters[0] = new SqlParameter("@Usernama", admin.Username);
                parameters[1] = new SqlParameter("@PassWord", admin.Password);

                sqlDataAdapter = new SqlDataAdapter("AdminLogin", sqlConnection) { SelectCommand = { CommandType = CommandType.StoredProcedure } };
                sqlDataAdapter.SelectCommand.Parameters.AddRange(parameters);
                var ds = new DataSet();
                sqlDataAdapter.Fill(ds);
                sqlConnection.Close();
                if (ds.Tables[0].Rows.Count > 0)
                {
                    var a = new AdminModels
                                {
                                    AdminID = (int)ds.Tables[0].Rows[0]["AdminID"],
                                    Username = (string)ds.Tables[0].Rows[0]["Username"],
                                    Password = (string)ds.Tables[0].Rows[0]["PassWord"],
                                    AdminName = (string)ds.Tables[0].Rows[0]["AdminName"]
                                };
                    Session.Remove("AdminID");
                    Session.Remove("AdminName");
                    Session.Add("AdminID", a.AdminID);
                    Session.Add("AdminName", a.AdminName);
                    _admin = a;
                    return PartialView("Login", a);
                }
                ViewData["MessageError"] = "Username and password incorrect";
                return PartialView("Login");
            }
            catch (Exception)
            {
                ViewData["MessageError"] = "Unknown Error!";
                return PartialView("Login");
            }
        }


        public ActionResult Logout()
        {
            sleep();
            if (Session["AdminID"] == null || _admin == null)
            {
                ViewData["MessageError"] = "You haven't loggin!";
                return PartialView("Login");
            }
            ViewData["MessageSuccess"] = "Logged Out!";
            _admin = null;
            Session.RemoveAll();
            return PartialView("Login");
        }


        // GET: /Admin/AdministratorDetails/
        public ActionResult AdministratorDetails()
        {
            sleep();
            if (Session["AdminID"] == null || _admin == null)
            {
                ViewData["MessageError"] = "You haven't loggin!";
                return PartialView("Login");
            }

            var ds = new DataSet();

            sqlConnection = getConnection();
            var pr = new SqlParameter("@AdminID", (int)Session["AdminID"]);

            sqlDataAdapter = new SqlDataAdapter("AdminDetailsByID", sqlConnection) { SelectCommand = { CommandType = CommandType.StoredProcedure } };
            sqlDataAdapter.SelectCommand.Parameters.Add(pr);


            sqlDataAdapter.Fill(ds);
            sqlConnection.Close();
            if (ds.Tables[0].Rows.Count > 0)
            {
                var a = new AdminModels
                            {
                                AdminID = (int)ds.Tables[0].Rows[0]["AdminID"],
                                Username = (string)ds.Tables[0].Rows[0]["Username"],
                                Password = (string)ds.Tables[0].Rows[0]["PassWord"],
                                AdminName = (string)ds.Tables[0].Rows[0]["AdminName"]
                            };
                return PartialView("AdministratorDetails", a);
            }
            return PartialView("AdministratorDetails");
        }
        // Update Infomations
        [HttpPost]
        public ActionResult ChangePass(AdminModels mdl)
        {
            try
            {
                sleep();
                if (Session["AdminID"] == null || _admin == null)
                {
                    ViewData["MessageError"] = "You haven't loggin!";
                    return PartialView("Login");
                }


                if (mdl.NewPassword != mdl.ConfirmPassword)
                {
                    ViewData["MessageError"] = "Confim password not match";
                    return PartialView("AdministratorDetails");
                }


                if (mdl.Password != _admin.Password)
                {
                    ViewData["MessageError"] = "Current password not correct";
                    return PartialView("AdministratorDetails");
                }



                mdl.NewPassword = globalController.password2md5(mdl.NewPassword);
                mdl.ConfirmPassword = globalController.password2md5(mdl.ConfirmPassword);
                mdl.Password = globalController.password2md5(mdl.Password);
                var pr = new[]
                             {
                                 new SqlParameter("@Username", mdl.Username),
                                 new SqlParameter("@PassWord", mdl.NewPassword),
                                 new SqlParameter("@AdminName", mdl.AdminName),
                                 new SqlParameter("@AdminID", mdl.AdminID)
                             };
                sqlConnection = getConnection();

                sqlCommand = new SqlCommand("UpdateAdminInfo", sqlConnection) { CommandType = CommandType.StoredProcedure };
                sqlCommand.Parameters.AddRange(pr);
                sqlCommand.ExecuteNonQuery();
                sqlConnection.Close();

                ViewData["MessageSuccess"] = "Changed Successfull!";
                _admin = mdl;

                return PartialView("AdministratorDetails", mdl);

            }
            catch (Exception ex)
            {
                ViewData["MessageError"] = ex.ToString();

                return PartialView("AdministratorDetails");
            }



        }

        public ActionResult AdminsList()
        {
            if (Session["AdminID"] == null || _admin == null)
            {
                ViewData["MessageError"] = "You haven't loggin!";
                return PartialView("Login");
            }
            sqlConnection = getConnection();
            sqlDataAdapter = new SqlDataAdapter("SELECT AdminID, UserName, PassWord, AdminName FROM dbo.Admins", sqlConnection);
            var ds = new DataSet();
            sqlDataAdapter.Fill(ds);
            sqlConnection.Close();


            var ada = ds.Tables[0];
            IList<AdminModels> list = (from DataRow r in ada.Rows
                                       select new AdminModels
                                                  {
                                                      AdminID = r.Field<int>("AdminID"),
                                                      Username = r.Field<string>("UserName"),
                                                      Password = r.Field<string>("PassWord"),
                                                      AdminName = r.Field<string>("AdminName")
                                                  }).ToList();
            return PartialView(list);
        }

        //AN ADMIN DETAILS
        public ActionResult Details(int id)
        {
            sqlConnection = getConnection();
            sqlDataAdapter = new SqlDataAdapter("SELECT AdminID, UserName, PassWord, AdminName FROM dbo.Admins WHERE AdminID =" + id, sqlConnection);
            var ds = new DataSet();
            sqlDataAdapter.Fill(ds);
            sqlConnection.Close();
            var r = ds.Tables[0].Rows[0];
            var mdl = new AdminModels
                {
                    AdminID = r.Field<int>("AdminID"),
                    Username = r.Field<string>("UserName"),
                    Password = r.Field<string>("PassWord"),
                    AdminName = r.Field<string>("AdminName")
                };
            return PartialView(mdl);
        }



        public ActionResult Create()
        {
            return PartialView("Create");
        }

        //
        // POST: /Admin/Create


        [HttpPost]
        public ActionResult Create(AdminModels mdl)
        {
            try
            {
                sleep();
                if (Session["AdminID"] == null || _admin == null)
                {
                    ViewData["MessageError"] = "You haven't loggin!";
                    return PartialView("Login");
                }

                if (mdl.NewPassword != mdl.ConfirmPassword)
                {
                    ViewData["MessageError"] = "Confim password not match";
                    return PartialView("Create");
                }
                if (String.IsNullOrEmpty(mdl.NewPassword) || String.IsNullOrEmpty(mdl.ConfirmPassword))
                {
                    return PartialView("Create");
                }
                mdl.NewPassword = globalController.password2md5(mdl.NewPassword);
                mdl.ConfirmPassword = globalController.password2md5(mdl.ConfirmPassword);

                var pr = new[]
                             {
                                 new SqlParameter("@Username", mdl.Username),
                                 new SqlParameter("@PassWord", mdl.NewPassword),
                                 new SqlParameter("@AdminName", mdl.AdminName)
                             };
                sqlConnection = getConnection();

                sqlCommand = new SqlCommand("InsertAdmin", sqlConnection) { CommandType = CommandType.StoredProcedure };
                sqlCommand.Parameters.AddRange(pr);
                sqlCommand.ExecuteNonQuery();
                sqlConnection.Close();

                ViewData["MessageSuccess"] = "Added succesfull" + mdl.Username;
                return PartialView("Create", mdl);

            }
            catch (Exception ex)
            {
                ViewData["MessageError"] = ex.Data.ToString();

                return PartialView("Create");
            }

        }

        //
        // GET: /Admin/Edit/5

        public ActionResult Edit(int id)
        {
            sleep();
            if (Session["AdminID"] == null || _admin == null)
            {
                ViewData["MessageError"] = "You haven't loggin!";
                return PartialView("Login");
            }

            if (id < 0)
            {
                ViewData["MessageError"] = "Please select an account";
                return PartialView("Message");
            }

            try
            {
                var ds = new DataSet();
                sqlConnection = getConnection();
                var pr = new SqlParameter("@AdminID", id);

                sqlDataAdapter = new SqlDataAdapter("AdminDetailsByID", sqlConnection) { SelectCommand = { CommandType = CommandType.StoredProcedure } };
                sqlDataAdapter.SelectCommand.Parameters.Add(pr);


                sqlDataAdapter.Fill(ds);
                sqlConnection.Close();
                if (ds.Tables[0].Rows.Count > 0)
                {
                    var a = new AdminModels
                    {
                        AdminID = (int)ds.Tables[0].Rows[0]["AdminID"],
                        Username = (string)ds.Tables[0].Rows[0]["Username"],
                        Password = (string)ds.Tables[0].Rows[0]["PassWord"],
                        AdminName = (string)ds.Tables[0].Rows[0]["AdminName"]
                    };
                    return PartialView("Edit", a);
                }
                return PartialView();
            }
            catch
            {
                ViewData["MessageError"] = "Erorr! Can not delete this account";
                return PartialView("Message");
            }


        }

        //
        // POST: /Admin/Edit/5

        [HttpPost]
        public ActionResult Edit(int id, AdminModels adm)
        {
            sleep();
            if (Session["AdminID"] == null || _admin == null)
            {
                ViewData["MessageError"] = "You haven't loggin!";
                return PartialView("Login");
            }

            if (adm.NewPassword != adm.ConfirmPassword)
            {
                ViewData["MessageError"] = "Confim password not match";
                return PartialView("Edit");
            }

            adm.NewPassword = globalController.password2md5(adm.NewPassword);
            try
            {
                sqlConnection = getConnection();
                var pr = new[]
                             {
                                 
                                 new SqlParameter("@UserName", adm.Username),
                                 new SqlParameter("@PassWord", adm.NewPassword),
                                 new SqlParameter("@AdminName", adm.AdminName),
                                 new SqlParameter("@AdminID", id)
                             };

                sqlCommand = new SqlCommand("UpdateAdminInfo", sqlConnection) { CommandType = CommandType.StoredProcedure };
                sqlCommand.Parameters.AddRange(pr);
                sqlCommand.ExecuteNonQuery();
                sqlConnection.Close();
                ViewData["MessageSuccess"] = "Admin's infomations has been updated!";
                return PartialView("Edit", adm);
            }
            catch (Exception)
            {
                ViewData["MessageError"] = "Erorr! Can not update this account";
                return PartialView("Edit", adm);
            }
        }


        //
        // GET: /Admin/Delete/5

        public ActionResult Delete(int id)
        {
            if (id == _admin.AdminID)
            {
                ViewData["MessageError"] = "You cannot delete yourself!";
                return PartialView("Message");
            }

            try
            {
                sqlConnection = getConnection();
                sqlDataAdapter = new SqlDataAdapter("SELECT AdminID, UserName, PassWord, AdminName FROM dbo.Admins WHERE AdminID =" + id, sqlConnection);
                var ds = new DataSet();
                sqlDataAdapter.Fill(ds);
                sqlConnection.Close();
                var r = ds.Tables[0].Rows[0];
                var mdl = new AdminModels
                {
                    AdminID = r.Field<int>("AdminID"),
                    Username = r.Field<string>("UserName"),
                    Password = r.Field<string>("PassWord"),
                    AdminName = r.Field<string>("AdminName")
                };
                return PartialView(mdl);
            }
            catch (Exception)
            {
                ViewData["MessageError"] = "Error when getting account infomation!";
                return PartialView("Message");
            }


        }

        //
        // POST: /Admin/Delete/5

        [HttpPost]
        public ActionResult Delete(int id, AdminModels admin)
        {
            if (Session["AdminID"] == null || _admin == null)
            {
                ViewData["MessageError"] = "You haven't loggin!";
                return PartialView("Login");
            }

            try
            {
                sqlConnection = getConnection();
                sqlCommand = new SqlCommand("DELETE FROM dbo.Admins WHERE AdminID =" + id, sqlConnection);
                sqlCommand.ExecuteNonQuery();
                sqlConnection.Close();

                ViewData["MessageSuccess"] = "Deleted " + admin.Username;
                return PartialView("Message");

            }
            catch (Exception ex)
            {
                ViewData["MessageError"] = ex.ToString();
                return PartialView("Message");
            }
        }
    }
}
